/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jm.jmsql.database;

import com.jm.commons.fio.FileSystem;
import com.jm.commons.logging.LogSystem;
import com.jm.commons.ui.UIBounds;
import com.jm.jmsql.models.DriverComboBoxModel;
import com.jm.jmsql.objects.Database;
import com.jm.jmsql.utils.Settings;
import java.awt.Frame;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Michael L.R. Marques
 */
public class DatabaseManager extends javax.swing.JDialog implements DocumentListener {
    
    /**
     * 
     */
    public static final int SUCCESSFUL = 1;
    
    /**
     * 
     */
    public static final int UNSUCCESSFUL = 0;
    
    /**
     * 
     */
    private int option;

    /**
     * Creates new form Database
     * @param parent
     */
    public DatabaseManager(Frame parent) {
        super(parent);
        initComponents();
        UIBounds.setBounds(parent, this);
        this.mainPanel.setImage(new java.io.File("./images/optionslogo.png"));
        // Set the icon image
        try {
            setIconImage(ImageIO.read(getClass().getClassLoader().getResource("com/jm/jmsql/icons/database.png")));
        } catch (IOException ioe) {
            LogSystem.log(getClass(), getClass().getEnclosingMethod(), "Set the icon image", ioe);
        }
        // Add text listeners to the text boxes
        this.txtDriverFile.getDocument().addDocumentListener(this);
        this.txtDriverName.getDocument().addDocumentListener(this);
    }

    /**
     *
     * @param database
     */
    public void setDatabase(Database database) {
        if (database.isSystemDatabase()) {
            JOptionPane.showMessageDialog(null, "Cannot customize a system database", "Customize Database", JOptionPane.OK_OPTION);
            return;
        } else {
            this.txtDriverFile.setText(database.getLibrary().getAbsolutePath());
        }
        this.txtDriverName.setText(database.getName());

        try {
            this.cbxDrivers.setModel(new DriverComboBoxModel(database.getLibrary()));
            this.cbxDrivers.setSelectedItem(database.getClassName());
        } catch (IOException ioe) {
            LogSystem.log(getClass(), getClass().getEnclosingMethod(), "Set the database", ioe);
        }
        this.txtDriverName.setEditable(false);
        this.btnDone.setEnabled(true);
    }

    /**
     *
     * @return
     */
    public Database getDatabase() {
        return this.option == SUCCESSFUL ? new Database(this.txtDriverName.getText(), this.cbxDrivers.getSelectedItem().toString(), this.txtDriverFile.getText()) : null;
    }

    /**
     *
     * @return
     */
    public int showDialog() {
        this.option = UNSUCCESSFUL;
        setVisible(true);
        return this.option;
    }
    
    /**
     * 
     * @param e 
     */
    @Override public void insertUpdate(DocumentEvent e) {
        this.btnDone.setEnabled(new File(this.txtDriverFile.getText()).exists() &&
                                    !this.txtDriverName.getText().isEmpty() &&
                                        this.cbxDrivers.getSelectedItem() != null);
    }
    
    /**
     * 
     * @param e 
     */
    @Override public void removeUpdate(DocumentEvent e) {
        this.btnDone.setEnabled(new File(this.txtDriverFile.getText()).exists() &&
                                    !this.txtDriverName.getText().isEmpty() &&
                                        this.cbxDrivers.getSelectedItem() != null);
    }
    
    /**
     * 
     * @param e 
     */
    @Override public void changedUpdate(DocumentEvent e) {
        this.btnDone.setEnabled(new File(this.txtDriverFile.getText()).exists() &&
                                    !this.txtDriverName.getText().isEmpty() &&
                                        this.cbxDrivers.getSelectedItem() != null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new com.jm.commons.components.panel.ImagePanel();
        txtDriverFile = new com.jm.commons.components.textfield.HintJTextField();
        cbxDrivers = new javax.swing.JComboBox();
        txtDriverName = new com.jm.commons.components.textfield.HintJTextField();
        btnBrowse = new javax.swing.JButton();
        btnDone = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Database Driver Manager");
        setBounds(new java.awt.Rectangle(0, 0, 440, 138));
        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(440, 138));
        setModal(true);
        setResizable(false);

        mainPanel.setImage(new java.io.File("C:\\Users\\Michael\\Documents\\NetBeansProjects\\JMSql\\images\\optionslogo.png"));

        txtDriverFile.setEditable(false);
        txtDriverFile.setHintText("Database Driver Library File...");
        txtDriverFile.setText("Database Driver Library File...");
        txtDriverFile.setBackground(new java.awt.Color(255, 255, 255));

        txtDriverName.setHintText("Database Driver Name...");
        txtDriverName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                done(evt);
            }
        });

        btnBrowse.setText("...");
        btnBrowse.setToolTipText("");
        btnBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Browse(evt);
            }
        });

        btnDone.setText("Done");
        btnDone.setEnabled(false);
        btnDone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                done(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbxDrivers, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDriverName, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 147, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnDone))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(txtDriverFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnBrowse, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap(100, Short.MAX_VALUE)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDriverFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBrowse))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbxDrivers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtDriverName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnDone)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void Browse(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Browse
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setFileFilter(new JarFileFilter());
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setCurrentDirectory(this.txtDriverFile.getText().isEmpty() ? Settings.getDatabaseLibrarysDirectory() : new File(this.txtDriverFile.getText()).getParentFile());
        if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(this)) {
            this.txtDriverFile.setText(fileChooser.getSelectedFile().getAbsolutePath());
            try {
                this.cbxDrivers.setModel(new DriverComboBoxModel(fileChooser.getSelectedFile()));
            } catch (IOException ioe) {
                LogSystem.log(getClass(), getClass().getEnclosingMethod(), "Build the DriverComboBoxModel from a Jar file", ioe);
            }
        }
    }//GEN-LAST:event_Browse

    private void done(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_done
        // Done button must be enabled
        if (!this.btnDone.isEnabled()) {
            return;
        }
        // Set the option as successful
        this.option = SUCCESSFUL;
        // Copy library file
        File driverFile = new File(this.txtDriverFile.getText());
        File newDriverFile = new File(Settings.getDatabaseLibrarysDirectory() + "/" + driverFile.getName());
        if (!newDriverFile.exists()) {
            FileSystem.copyFile(driverFile, newDriverFile);
        }
        // Hide the database manager
        setVisible(false);
    }//GEN-LAST:event_done

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBrowse;
    private javax.swing.JButton btnDone;
    private javax.swing.JComboBox cbxDrivers;
    private com.jm.commons.components.panel.ImagePanel mainPanel;
    private com.jm.commons.components.textfield.HintJTextField txtDriverFile;
    private com.jm.commons.components.textfield.HintJTextField txtDriverName;
    // End of variables declaration//GEN-END:variables

    /**
     *
     */
    private class JarFileFilter extends FileFilter {

        /**
         *
         * @param f
         * @return
         */
        @Override public boolean accept(File f) {
            return f.isDirectory()
                    || FileSystem.isValidExtension(f, new String[]{"jar"});
        }

        /**
         *
         * @return
         */
        @Override public String getDescription() {
            return "Jar Files (*.jar)";
        }
    }
    
}
